package com.beiing.tianshuai.tianshuai.mine.ui.fragment;


import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.RadioButton;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.activity.MainActivity;
import com.beiing.tianshuai.tianshuai.adapter.PersonalPublishInterestAdapter;
import com.beiing.tianshuai.tianshuai.app.AppConstant;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.base.BaseFragment;
import com.beiing.tianshuai.tianshuai.entity.CodeBean;
import com.beiing.tianshuai.tianshuai.entity.PersonalPublishBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.freshnews.DiscoveryDetailActivity;
import com.beiing.tianshuai.tianshuai.huodong.ActivitiesDetailActivity;
import com.beiing.tianshuai.tianshuai.interest.InterestVideoDetailActivity;
import com.beiing.tianshuai.tianshuai.mine.presenter.PersonalPublishPresenter;
import com.beiing.tianshuai.tianshuai.mine.view.PersonalPublishViewImpl;
import com.beiing.tianshuai.tianshuai.util.DensityUtils;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.util.NetBitmapUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomEmptyLayout;
import com.beiing.tianshuai.tianshuai.widget.MyRefreshHeader;
import com.beiing.tianshuai.tianshuai.widget.RecycleViewDivider;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.open.utils.ThreadManager;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.tianshuai.easypopup.EasyPopup;
import com.tianshuai.easypopup.HorizontalGravity;
import com.tianshuai.easypopup.VerticalGravity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Create by Jinni 2017-12-25
 * 投稿界面的兴趣投稿fragment
 */
public class PersonalPublishInterestFragment extends BaseFragment implements PersonalPublishViewImpl {

    /**
     * 刷新头布局
     */
    @BindView(R.id.srl_my_refresh_layout)
    SmartRefreshLayout mSrlMyRefreshLayout;

    /**
     * 刷新头布局
     */
    @BindView(R.id.refresh_layout_header)
    MyRefreshHeader mRefreshLayoutHeader;

    /**
     * 数据列表RecyclerView
     */
    @BindView(R.id.rv_interests_published)
    RecyclerView mRvInterestsPublished;

    /**
     * 加载视图
     */
    @BindView(R.id.empty_view)
    CustomEmptyLayout mCustomEmptyLayout;

    private static final String TAG = "PersonalPublishInterest";

    /**
     * 每页最多显示的条目数量
     */
    public static final int PAGE_SIZE = 15;

    /**
     * 当前页码
     */
    private int page = 1;

    /**
     * presenter
     */
    private PersonalPublishPresenter mPresenter;

    /**
     * 当前所查看的用户id
     */
    private String mUid;

    /**
     * 是否处于刷新状态
     */
    private boolean isRefresh = true;

    /**
     * 是否已经加载完成
     */
    private boolean isLoadFinished;

    /**
     * 列表数据适配器
     */
    private PersonalPublishInterestAdapter mAdapter;

    /**
     * 当前视图展示数据的类型
     * 0-兴趣 1-活动 2-发现
     */
    private int mType;

    /**
     * 网络请求失败的时候进行重连的次数
     */
    private int retryConnectCount;

    /**
     * 更多菜单弹窗
     */
    private EasyPopup mPopup;

    /**
     * 分享弹窗
     */
    private Dialog bottomDialog;

    /**
     * 分享的缩略图
     */
    private Bitmap thumb;

    /**
     * 第三方分享
     */
    private Tencent mTencent;

    /**
     * 分享监听事件
     */
    private IUiListener mIUiListener = new IUiListener() {
        @Override
        public void onComplete(Object o) {
            showShortText("分享成功");
        }

        @Override
        public void onError(UiError uiError) {
            showShortText("分享失败");
        }

        @Override
        public void onCancel() {
            showShortText("取消分享");
        }
    };

    public static PersonalPublishInterestFragment newInstance(String uid, int type) {
        PersonalPublishInterestFragment fragment = new PersonalPublishInterestFragment();
        Bundle bundle = new Bundle();
        bundle.putString("uid", uid);
        bundle.putInt("type", type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_personal_publish_interest;
    }

    @Override
    protected void init(View convertView) {
        Bundle arguments = getArguments();
        if (arguments != null) {
            mPopup = new EasyPopup(getActivity())
                    .setContentView(R.layout.menu_personal_publish_more)
                    .setAnimationStyle(R.style.QQPopAnim)
                    .setFocusAndOutsideEnable(true)
                    .createPopup();
            mTencent = Tencent.createInstance("1106377834", mContext);
            mCustomEmptyLayout.setInProgress();
            mUid = arguments.getString("uid");
            mType = arguments.getInt("type");
            initRefreshLayout();
            initRecyclerView();
            initPresenter();
            initListener();
        }
    }

    /**
     * 初始化refresh layout
     * 设置下拉和上拉动作的listener
     */
    private void initRefreshLayout() {
        mSrlMyRefreshLayout.setRefreshHeader(new MyRefreshHeader(mContext));
        mSrlMyRefreshLayout.setRefreshFooter(new ClassicsFooter(mContext));
        // =================== 下拉刷新 =====================
        mSrlMyRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                isRefresh = true;
                isLoadFinished = false;
                mPresenter.getPersonalPublishData(mUid, PAGE_SIZE, page, mType);
            }
        });
        // =================== 上拉加载 =====================
        mSrlMyRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (!isLoadFinished) {
                    page++;
                    isRefresh = false;
                    mPresenter.getPersonalPublishData(mUid, PAGE_SIZE, page, mType);
                }
            }
        });
    }

    private void initRecyclerView() {

        // 设置布局管理器
        LinearLayoutManager manager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        mRvInterestsPublished.setLayoutManager(manager);

        // 设置适配器
        mAdapter = new PersonalPublishInterestAdapter(mContext, mType);
        mRvInterestsPublished.setAdapter(mAdapter);

        // 设置分割线
        mRvInterestsPublished.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL, DensityUtils.dp2px(mContext, 0.5f),
                ContextCompat.getColor(mContext, R.color.common_gray_background))
        );

    }

    /**
     * 初始化presenter
     */
    private void initPresenter() {
        mPresenter = new PersonalPublishPresenter(this);
        mPresenter.getPersonalPublishData(mUid, PAGE_SIZE, page, mType);
    }

    /**
     * 设置监听事件
     */
    private void initListener() {

        // 弹出菜单
        mAdapter.setMoreClickListener(new PersonalPublishInterestAdapter.OnMoreClickListener() {
            @Override
            public void onMoreClick(View view, PersonalPublishBean.DataBeanX.DataBean bean, int position, int type) {
                initPopupWindow(bean, type, position);
                int i = view.getLayoutParams().width / 2 - DensityUtils.dp2px(mContext, 12);
                mPopup.showAtAnchorView(view, VerticalGravity.BELOW, HorizontalGravity.ALIGN_RIGHT, i, -DensityUtils.dp2px(mContext, 15));
            }
        });

        // 条目点击事件
        mAdapter.setItemClickListener(new PersonalPublishInterestAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(PersonalPublishBean.DataBeanX.DataBean bean, int position, int type) {
                if (TextUtils.isEmpty(bean.getId())) {
                    throw new IllegalStateException("条目id不存在");
                }
                Intent intent = new Intent();
                switch (type) {
                    case 0:
                        intent.setClass(mContext, InterestVideoDetailActivity.class);
                        intent.putExtra("vid", bean.getId());
                        startActivity(intent);
                        break;
                    case 1:
                        intent.setClass(mContext, ActivitiesDetailActivity.class);
                        intent.putExtra("active_id", bean.getId());
                        startActivity(intent);
                        break;
                    case 2:
                        intent.setClass(mContext, DiscoveryDetailActivity.class);
                        intent.putExtra("fresh_id", bean.getId());
                        startActivity(intent);
                        break;
                }
            }
        });
    }

    /**
     * 初始化更多菜单
     *
     * @param bean     数据的实体
     * @param type     当前分页的类别
     * @param position 条目所在位置
     */
    private void initPopupWindow(final PersonalPublishBean.DataBeanX.DataBean bean, final int type, final int position) {

        // 分享
        TextView menuBtnShare = mPopup.getView(R.id.btn_share);
        menuBtnShare.setOnClickListener(new View.OnClickListener() {

            private String mSummary;
            private String mTitle;
            private String mUrl;
            private String mCover;

            @Override
            public void onClick(View view) {
                switch (type) {
                    case 0:
                        mCover = HttpRequestConstant.VIDEO_PIC_HEAD + bean.getCover();
                        mUrl = "http://www.tianshuai.com.cn/index.php/Home/video/video_web/id/" + bean.getId();
                        mTitle = bean.getTitle();
                        mSummary = bean.getContent();
                        showShareDialog(mCover, mUrl, mTitle, mSummary);
                        break;
                    case 1:
                        mCover = HttpRequestConstant.ACTIVITY_PIC_HEAD + bean.getCover();
                        mUrl = "http://www.tianshuai.com.cn/index.php/Home/Active/page2/id/" + bean.getId();
                        mTitle = bean.getStrech();
                        mSummary = bean.getStrech();
                        showShareDialog(mCover, mUrl, mTitle, mSummary);
                        break;
                    case 2:
                        String[] split;
                        if (!TextUtils.isEmpty(bean.getCover())) {
                            split = bean.getCover().split(",");
                            mCover = HttpRequestConstant.FRESH_COVER_URL + split[0];
                        } else {
                            mCover = null;
                        }
                        mUrl = "http://www.tianshuai.com.cn/index.php/Home/Active/news_detail/id/" + bean.getId();
                        mTitle = bean.getTitle();
                        mSummary = bean.getTitle();
                        showShareDialog(mCover, mUrl, mTitle, mSummary);
                        break;
                }
                mPopup.dismiss();
            }
        });

        // 删除 如果查看的投稿所属用户为当前用户显示删除按钮 否则隐藏删除按钮
        TextView menuBtnDelete = mPopup.getView(R.id.btn_delete);
        if (mUid.equals(UserInfoBean.getUid(mContext))) {
            menuBtnDelete.setVisibility(View.VISIBLE);
            menuBtnDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    switch (type) {
                        case 0:
                            mPresenter.getDeleteMyInterestResult(UserInfoBean.getUid(mContext), bean.getId(), position);
                            break;
                        case 1:
                            mPresenter.getDeleteMyActivityResult(bean.getId(), position);
                            break;
                        case 2:
                            mPresenter.getDeleteMyDiscoveryResult(bean.getId(), position);
                            break;
                    }
                    mPopup.dismiss();
                }
            });
        } else {
            menuBtnDelete.setVisibility(View.GONE);
        }
    }

    /**
     * 弹出分享提示框
     *
     * @param cover   封面
     * @param url     链接
     * @param title   标题
     * @param summary 描述
     */
    private void showShareDialog(final String cover, final String url, final String title, final String summary) {
        bottomDialog = new Dialog(mContext, R.style.BottomDialog);
        @SuppressLint("InflateParams") View contentView = LayoutInflater.from(mContext).inflate(R.layout.dialog_personal_publish, null);
        RadioButton weChatFriends = contentView.findViewById(R.id.rb_wechat_friends);
        RadioButton weChatCircle = contentView.findViewById(R.id.rb_wechat_circle);
        RadioButton qqFriends = contentView.findViewById(R.id.rb_qq_friends);
        RadioButton qqZone = contentView.findViewById(R.id.rb_qzone);

        weChatFriends.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareToWeChatWithWebPage(cover, mContext, url, title, summary, 0);
                bottomDialog.dismiss();
            }
        });
        weChatCircle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareToWeChatWithWebPage(cover, mContext, url, title, summary, 1);
                bottomDialog.dismiss();
            }
        });
        qqFriends.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareToQQ(title, summary, url);
                bottomDialog.dismiss();
            }
        });
        qqZone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareToQZone(title, summary, url);
                bottomDialog.dismiss();
            }
        });

        bottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        Window window = bottomDialog.getWindow();
        if (window != null) {
            window.setGravity(Gravity.BOTTOM);
            window.setWindowAnimations(R.style.BottomDialog_Animation);
        }
        bottomDialog.show();
        bottomDialog.setCanceledOnTouchOutside(true);
    }

    private void shareToWeChatWithWebPage(final String cover, Context context, String url, String title, String description, final int scene) {
        final IWXAPI iwxapi = WXAPIFactory.createWXAPI(context, AppConstant.WX_APP_ID);

        if (!iwxapi.isWXAppInstalled()) {
            showShortText("您尚未安装微信");
            return;
        }

        WXWebpageObject wxWebpageObject = new WXWebpageObject();
        wxWebpageObject.webpageUrl = url;
        final WXMediaMessage wxMediaMessage = new WXMediaMessage(wxWebpageObject);
        wxMediaMessage.mediaObject = wxWebpageObject;
        wxMediaMessage.title = title;
        wxMediaMessage.description = description;
        new Thread(new Runnable() {
            @Override
            public void run() {

                if (!TextUtils.isEmpty(cover)) {
                    thumb = NetBitmapUtils.getBitmap(cover);
                    thumb = Bitmap.createScaledBitmap(thumb, 200, 200, true);
                } else {
                    thumb = null;
                }

                wxMediaMessage.setThumbImage(thumb);

                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = String.valueOf(System.currentTimeMillis());
                req.message = wxMediaMessage;
                req.scene = scene;

                iwxapi.sendReq(req);
            }
        }).start();
    }

    private void shareToQQ(String title, String summary, String url) {
        final Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, title);         //标题
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, summary);     //摘要
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, url);      //内容地址

        ThreadManager.getMainHandler().post(new Runnable() {
            @Override
            public void run() {
                mTencent.shareToQQ((MainActivity) mContext, params, mIUiListener);
            }
        });
    }

    private void shareToQZone(String title, String summary, String url) {
        final Bundle params = new Bundle();
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);         //标题
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, summary);     //摘要
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, url);      //内容地址
        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, new ArrayList<String>());

        ThreadManager.getMainHandler().post(new Runnable() {
            @Override
            public void run() {
                mTencent.shareToQzone((MainActivity) mContext, params, mIUiListener);
            }
        });
    }

    @Override
    public void showProgress() {
        if (mCustomEmptyLayout != null) {
            mCustomEmptyLayout.setInProgress();
        }
    }

    @Override
    public void hideProgress() {
        if (mCustomEmptyLayout != null) {
            mCustomEmptyLayout.setChildrenVisible();
        }
    }

    @Override
    public void onRequestSuccess(PersonalPublishBean bean) {
        if (bean.getCode() == 200) {
            List<PersonalPublishBean.DataBeanX.DataBean> data = bean.getData().getData();
            if (isRefresh) {
                int size = data.size();
                mAdapter.updateData(data);
                if (size == PAGE_SIZE) {
                    isLoadFinished = false;
                    mSrlMyRefreshLayout.setLoadmoreFinished(false);
                    if (mCustomEmptyLayout != null) {
                        mCustomEmptyLayout.setChildrenVisible();
                    }
                } else if (size > 0 && size < PAGE_SIZE) {
                    isLoadFinished = true;
                    mSrlMyRefreshLayout.setLoadmoreFinished(true);
                    if (mCustomEmptyLayout != null) {
                        mCustomEmptyLayout.setChildrenVisible();
                    }
                } else if (size == 0) {
                    isLoadFinished = true;
                    mSrlMyRefreshLayout.setLoadmoreFinished(true);
                    mCustomEmptyLayout.setEmptyView(R.drawable.video_empty_warning, "这里还是空空的");
                }
            } else {
                int size = data.size();
                mAdapter.appendData(data);
                if (size == PAGE_SIZE) {
                    mSrlMyRefreshLayout.setLoadmoreFinished(false);
                } else if (size > 0 && size < PAGE_SIZE) {
                    isLoadFinished = true;
                    mSrlMyRefreshLayout.setLoadmoreFinished(true);
                } else if (size == 0) {
                    isLoadFinished = true;
                    mSrlMyRefreshLayout.setLoadmoreFinished(true);
                }
            }
            if (mSrlMyRefreshLayout.isRefreshing()) {
                mSrlMyRefreshLayout.finishRefresh(true);
            }
            if (mSrlMyRefreshLayout.isLoading()) {
                mSrlMyRefreshLayout.finishLoadmore(true);
            }
        } else {
            LogUtils.e(bean.getCode() + " " + bean.getData().getNumber(), PersonalPublishInterestFragment.class.getName());
            if (mSrlMyRefreshLayout.isRefreshing()) {
                mSrlMyRefreshLayout.finishRefresh(false);
            }
            if (mSrlMyRefreshLayout.isLoading()) {
                mSrlMyRefreshLayout.finishLoadmore(false);
            }
        }
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        if (retryConnectCount < 5) {
            retryConnectCount++;
            mPresenter.getPersonalPublishData(mUid, PAGE_SIZE, page, mType);
        } else {
            retryConnectCount = 0;
            LogUtils.e(throwable.getMessage(), TAG);
            showShortText("请求失败");
        }
    }

    @Override
    public void onDeleteSuccess(CodeBean bean, int position) {
        mAdapter.removeData(position);
        if (mAdapter.getList().size() == 0) {
            mCustomEmptyLayout.setEmptyView(R.drawable.video_empty_warning, "这里还是空空的");
        }
    }

    @Override
    public void onDeleteError(Throwable throwable) {
        showShortText("请求失败");
    }
}
